var xlsx = require("node-xlsx");
var fs = require('fs');
var file_util = require('./public/file_util');
var path = require('path');

var data_path = process.argv[3];
var mapSurface_path = process.argv[4];
var export_s_path = process.argv[5]
var deleteDir = process.argv[6]


const NAME = 0;
const VALUE = 0;
const LANG = 2;
const TEMPLATE = 1;
const DATA = 0;

//解析Excel
function praseExcel(list, export_dir, type, xlsxName) {
	if (list.length <= 0) {
		return;
	}
	console.log("list.length ", list.length);

	var lang_path = path.join(export_dir, 'lang')
	var json_path = path.join(export_dir, 'json')
	//var ts_path = path.join(export_dir,'ts')
	var class_path = path.join(export_dir, 'class')
	//合并文件
	var bigObj = {};
	bigObj["data"] = {};
	var headConfig = list[0].data;
	console.log(" headconfig ", headConfig);
	var head_info_type = headConfig[0][1];
	console.log(" head_info_type ", head_info_type);

	if(head_info_type == "C" || head_info_type == "c") {
		return;
	}

	var head_info_type_arr =[];
	for(var i = 1; i < headConfig.length; i ++){
		head_info_type_arr[i] = headConfig[i][1];
		console.log(" head_info_type_arr[",i,"] ", head_info_type_arr[i]);
	}

	var bigFileName = headConfig[NAME][VALUE];
	//var targetDir = export_dir+"/"+bigFileName;
	var targetDir = export_dir+"/"+xlsxName;
	file_util.createDir(export_dir); //创建同名文件夹
	file_util.createDir(targetDir); //创建同名文件夹
	console.log("name is ", NAME, " value ", VALUE, " bigFileName ", bigFileName, " export_dir ", export_dir, " targetDir ", targetDir);

	for (var i = 1; i < list.length; i++) {
		if (!headConfig[i]) {
			continue;
		}
		if(type == "c"){
			if(head_info_type_arr[i] == "S"){
			    continue;
            }
        }
        else if(type == "s"){
            if(head_info_type_arr[i] == "C"){
            	continue;
            }
        }

		var excleData = list[i].data;
		var dataArray = [];
		var nameArray = excleData[0]; // 第一行 说明
		var keyArray = excleData[1]; //第二行 名称
		var typeArray = excleData[2]; // 第三行 类型
		var scArray = excleData[3]; // 第四行 导出类别 s 服务器  c 客户端 sc 服务器与客户端。
		var index = 0;
		

		var sheetName = headConfig[i][VALUE];
		console.log(" i ", i, " sheetname", sheetName);
		sheetName = sheetName.substring(0, sheetName.length-5);

		//drop table t_***_conf

		//create table t_***_conf

		//insert into t_***_conf (**,**,**) values ();
		var template_insert_str = "insert into t_"+sheetName+"_conf (%sKey%) values (%sValue%);"
		var sKey = "";
		for (var kk = 0; kk < keyArray.length; kk++) {
			if(scArray[kk] == "C" || scArray[kk] == "NULL" || scArray[kk] == "null") {
				continue;
			}

			var kkk = 0;
			var string2 = '';
			while ( kkk <= keyArray[kk].length ) {
			    var ch = keyArray[kk].charAt( kkk );
			    if (( ch >= 'A' ) && ( ch <= 'Z' )) {
			        ch = "_"+ch.toLowerCase();
			    }
			    string2 += ch;
			    kkk++;
			}

			sKey = sKey + string2 +",";
		}
		sKey = sKey.substring(0, sKey.length-1);
		template_insert_str = template_insert_str.replace('%sKey%', sKey);

		var undf = 'undefined';
		//rows
		let ws = fs.createWriteStream(targetDir+"/" + sheetName + ".sql");
		ws.write("truncate table t_"+sheetName+"_conf;\r\n");
		for (var j = 4; j < excleData.length; j++) {
			var curData = excleData[j];
			if (curData.length == 0) continue;
			//slots
			var sValue = "";
			for (var kk = 0; kk < keyArray.length; kk++) {
				if(scArray[kk] == "C" || scArray[kk] == "NULL" || scArray[kk] == "null") {
					continue;
				}

				if (typeArray[kk] == 's') {
					var slot = curData[kk];
					if (undf == slot || typeof(slot) == "undefined") {
						curData[kk] = "";
					}
				}
				if (typeArray[kk] == "i" || typeArray[kk] == "f" || typeArray[kk] == "l") {
					sValue = sValue + curData[kk]+",";
				} else {
					sValue = sValue + "'"+curData[kk]+"',";
				}	
			}
			ws.write(template_insert_str.replace('%sValue%', sValue.substring(0, sValue.length-1)) + '\r\n');
		}
		console.log(' 关闭通道 ......')
		ws.close();// 关闭通道
	}
	console.log("qqq");
}


function parseMapSurface(subpath, exportPath, currFileName) {
	const jsonData = JSON.parse(file_util.readFile(subpath));
	console.log('=================== 读取MapSurface ===================' + currFileName);
	let ws = fs.createWriteStream(exportPath+"/" + currFileName + ".sql");
	ws.write("DROP TABLE IF EXISTS `db_lad_logic`.`t_"+currFileName+"_conf`;\r\n"); 
	ws.write("CREATE TABLE `db_lad_logic`.`t_"+currFileName+"_conf`(\r\n"); 
	ws.write("`id` bigint(11) unsigned NOT NULL COMMENT 'id 主键',\r\n"); 
	ws.write("`brush_id` int(7) unsigned DEFAULT '0' COMMENT '笔刷id',\r\n"); 
	ws.write("`x` int(7) unsigned DEFAULT '0' COMMENT '坐标x',\r\n"); 
	ws.write("`y` int(7) unsigned DEFAULT '0' COMMENT '坐标y',\r\n"); 
	ws.write("PRIMARY KEY (`id`)\r\n"); 
	ws.write(") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;\r\n\r\n"); 

	ws.write("truncate table t_"+currFileName+"_conf;\r\n"); 
	var template_insert_str = "insert into t_"+currFileName+"_conf (id, brush_id, x, y) values (%sValue%);"

	var id = 1000;
	var one = jsonData["List"];
	for (var i = 0; i < one.length; i++) {
		var BrushId = one[i]["BrushId"];
		var ll = one[i]["List"];
		for (var j = 0; j < ll.length; j++) {
			var pos = ll[j];
			id++;
			var sVal = id+","+BrushId+","+pos["x"]+","+pos["y"];
			ws.write(template_insert_str.replace('%sValue%', sVal) + '\r\n');
		}
	}
	ws.close();
}


var ignoreFileList = ['脚本数据', 'test']
function parseFile(fileName, exportPath, type) {
	console.log("parseFile  fileName ", fileName)
	for (var i = 0; i < ignoreFileList.length; i++) {
		if (fileName.indexOf(ignoreFileList[i]) >= 0) {
			return;
		}
	}
	praseExcel(xlsx.parse(fileName), exportPath, type, fileName.substring(fileName.lastIndexOf("\\")+1, fileName.lastIndexOf(".")));
}

var readDir_s = function(dir, exportPath, isMapSurface) {

	console.log(' readDir ===================')
	var stat = fs.statSync(dir);
	if (!stat.isDirectory()) {
		return;
	}
	var subpaths = fs.readdirSync(dir),
		subpath;
	for (var i = 0; i < subpaths.length; ++i) {
		if (subpaths[i][0] === '.') {
			continue;
		}
		subpath = path.join(dir, subpaths[i]);
		console.log(' readDir_s   subpath ',subpath)
		stat = fs.statSync(subpath);
		if (stat.isDirectory()) {
			// readDir(subpath, obj);
		} else if (stat.isFile()) { //是文件
			if (isMapSurface) {
				file_util.createDir(exportPath);
				var targetDir = exportPath+"/地表山河";
				file_util.createDir(targetDir);
				parseMapSurface(subpath, targetDir, subpaths[i].substring(0, subpaths[i].length-4));
			} else {
				parseFile(subpath, exportPath, "s");
			}
		}
	}
}


if (data_path && export_s_path) {
	if (deleteDir && deleteDir === "true") {
		file_util.delDir(export_s_path);
	}
	readDir_s(data_path, export_s_path, false);
	//readDir_s(mapSurface_path, export_s_path, true);
}

module.exports.readDir_s = readDir_s
